﻿using HandyControl.Controls;
using HandyControl.Tools;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace LpbPrj.Client.Controls;

/// <summary>
/// 图像背景
/// </summary>
public class ImageSourceExPropertyEditor : PropertyEditorBase
{
    public override FrameworkElement CreateElement(PropertyItem propertyItem)
    {
        var imageSelector = new ImageSourceSelector
        {
            IsEnabled = !propertyItem.IsReadOnly,
            Width = 50,
            Height = 50,
            HorizontalAlignment = HorizontalAlignment.Left,
            Style = ResourceHelper.GetResource<System.Windows.Style>("ImageSelectorDefaultStyle"),
        };

        BindingOperations.SetBinding(this, SourceProperty, new Binding(ImageSourceSelector.SourceProperty.Name)
        {
            Source = imageSelector,
            Mode = BindingMode.TwoWay,
        });

        return imageSelector;
    }

    public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
        nameof(Source), typeof(ImageSource), typeof(ImageSourceExPropertyEditor), new FrameworkPropertyMetadata(default(ImageSource), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
    public ImageSource Source
    {
        get => (ImageSource)GetValue(SourceProperty);
        set => SetValue(SourceProperty, value);
    }

    public override void CreateBinding(PropertyItem propertyItem, DependencyObject element)
        => BindingOperations.SetBinding(this, GetDependencyProperty(),
            new Binding($"({propertyItem.PropertyName})")
            {
                Source = propertyItem.Value,
                Mode = GetBindingMode(propertyItem),
                UpdateSourceTrigger = GetUpdateSourceTrigger(propertyItem),
                Converter = GetConverter(propertyItem)
            });

    public override DependencyProperty GetDependencyProperty() => SourceProperty;
}
